package com.jianhua.backend.controller;

import com.jianhua.backend.common.R;
import com.jianhua.backend.service.ImageService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/img")
@RequiredArgsConstructor
public class ImageController {

    private final ImageService imageService;

    // 允许上传的图片类型
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg",
            "image/png",
            "image/gif",
            "image/bmp",
            "image/webp"
    );

    @PostMapping("add")
    public R<?> addImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error(400, "上传文件不能为空");
        }

        // 检查文件类型
        if (!ALLOWED_IMAGE_TYPES.contains(file.getContentType())) {
            return R.error(400, "只能上传图片文件");
        }

        try {
            String imageUrl = imageService.addImage(file);
            return R.success("添加图片成功", imageUrl);
        } catch (Exception e) {
            return R.error(400, "上传图片失败: " + e.getMessage());
        }
    }
}